package com.battle.service.service.impl;

import com.battle.pojo.entity.TreeNode;
import com.battle.service.repository.in.TreeNodeRepository;
import com.battle.service.service.in.TreeNodeService;
import nirvana.core.utils.ids.IdGenerator;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 【描 述】：
 * 【环 境】：J2SE 17
 * 【详 细】：
 *
 * @author 李松林
 * @version v1.0 2024/5/3 新建
 * @since 2024/5/3
 */
@Service
public class TreeNodeServiceImpl implements TreeNodeService {

    private final TreeNodeRepository treeNodeRepository;

    public TreeNodeServiceImpl(TreeNodeRepository treeNodeRepository) {
        this.treeNodeRepository = treeNodeRepository;
    }


    /**
     * 添加树节点
     *
     * @param progenitor 祖代
     * @param descendant 子代
     */
    @Override
    public void addTreeNode(Long progenitor, Long descendant) {
        List<TreeNode> nodeList = treeNodeRepository.getProgenitorTreeNodes(progenitor);

        List<TreeNode> list = new ArrayList<>();
        for (TreeNode node : nodeList) {
            Integer distance = node.getDistance();
            distance++;
            node.setDistance(distance);
            node.setDescendant(descendant);
            node.setId(IdGenerator.SNOW.generate());
            list.add(node);
        }

        TreeNode treeNode = new TreeNode();

        treeNode.setDescendant(descendant);
        treeNode.setProgenitor(descendant);
        treeNode.setDistance(0);
        treeNode.setId(IdGenerator.SNOW.generate());

        list.add(treeNode);
        treeNodeRepository.saveBatch(list);
    }

    /**
     * 删除全部后代
     *
     * @param progenitor
     */
    @Override
    public void deleteDescendant(Long progenitor) {
        treeNodeRepository.deleteDescendant(progenitor);
    }
}
